from flask import Flask, request, jsonify, Response
from flask_cors import CORS
from .stock_analyzer import StockFinancialAnalyzer
import threading

app = Flask(__name__)
CORS(app)  # 允许跨域请求

# 全局分析器实例（线程安全）
analyzer_lock = threading.Lock()
analyzer = None

def init_analyzer():
    global analyzer
    with analyzer_lock:
        if analyzer is None:
            analyzer = StockFinancialAnalyzer()

@app.route('/')
def index():
    return 'Hello World'

@app.route('/get_financial_data', methods=['POST'])
def get_financial_data():
    data = request.json
    stock_input = data.get('stock_input')
    
    if not stock_input:
        return jsonify({'error': '缺少股票代码或名称'}), 400
    
    init_analyzer()
    
    try:
        financial_data = analyzer.get_financial_data(stock_input)
        return jsonify({'financial_data': financial_data})
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/analyze_financial_data', methods=['POST'])
def analyze_financial_data():
    data = request.json
    prompt_template = data.get('prompt_template')
    
    init_analyzer()
    
    def generate():
        def stream_callback(content):
            # 以SSE格式发送数据
            yield f"data: {content}\n\n"
        
        # 启动分析并流式输出
        for chunk in analyzer.analyze_financial_data(
            prompt_template=prompt_template,
            stream_callback=stream_callback
        ):
            yield from chunk
        
        yield "data: [DONE]\n\n"
    
    return Response(generate(), mimetype='text/event-stream')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, threaded=True)
